<template>
  <div class="relation-management">
    <!-- 搜索栏 -->
    <el-card shadow="hover" class="search-box">
      <el-input
          v-model="searchParams.categoryName"
          placeholder="输入分类名称"
          style="width: 240px"
          clearable
          @clear="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="success" @click="openDialog">新增关联</el-button>
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="data-table">
      <el-table
          :data="tableData"
          stripe
          v-loading="loading"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="categoryName" label="分类名称" />
        <el-table-column label="关联赛事">
          <template #default="{row}">
            <el-tag
                v-for="(name, index) in (row.eventNames || [])"
                :key="index"
                type="info"
                class="event-tag"
            >
              {{ name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{row}">
            <el-button
                type="primary"
                icon="Edit"
                circle
                @click="openDialog(row)"
            />
            <el-button
                type="danger"
                icon="Delete"
                circle
                @click="deleteRelation(row.categoryId)"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[5, 10, 15,20]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadData"
          @current-change="loadData"
      />
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑关联' : '新增关联'"
        width="600px"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="赛事分类" required>
          <el-select
              v-model="form.categoryId"
              placeholder="请选择赛事大类"
              filterable
              style="width: 100%"
              @change="handleCategoryChange"
          >
            <el-option
                v-for="category in categoryOptions"
                :key="category.id"
                :label="category.name"
                :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="关联赛事" required>
          <el-select
              v-model="form.eventIds"
              multiple
              placeholder="请选择具体赛事"
              filterable
              style="width: 100%"
          >
            <el-option
                v-for="event in eventOptions"
                :key="event.id"
                :label="event.name"
                :value="event.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">关联</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 数据状态
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const selectedIds = ref([])

const searchParams = reactive({
  categoryName: ''
})

const pagination = reactive({
  current: 1,
  size: 5,
  total: 0
})

const form = reactive({
  id: null,
  categoryId: null,
  eventIds: []
})

const tableData = ref([])
const categoryOptions = ref([])
const eventOptions = ref([])

// 生命周期钩子
onMounted(() => {
  loadData()
  loadCategories()
  loadEvents()
})

// 加载主数据
const loadData = async () => {
  try {
    loading.value = true
    const res = await request.get('/relations/search', {
      params: {
        categoryName: searchParams.categoryName,
        page: Math.max(1, pagination?.current || 1),
        size: Math.max(1, pagination?.size || 5)
      }
    })
    // 更新分页总数和表格数据
    pagination.total = res.total
    tableData.value = res.list ||[]
  } catch (error) {
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false // 确保加载完成后关闭加载状态
  }
}


// 加载赛事大类选项
const loadCategories = async () => {
  const res = await request.get('/relations/categories')
  categoryOptions.value = res
}

// 加载具体赛事选项
const loadEvents = async () => {
  const res = await request.get('/relations/events')
  eventOptions.value = res
}

// 打开对话框
const openDialog = (row = null) => {
  if (row) {
    isEdit.value = true
    form.id = row.id
    form.categoryId = row.categoryId
    loadRelationEvents(row.categoryId)
  } else {
    isEdit.value = false
    form.id = null
    form.categoryId = null
    form.eventIds = []
  }
  dialogVisible.value = true
}

// 分类选择变化时加载关联赛事
const handleCategoryChange = async (categoryId) => {
  if (categoryId) {
    await loadRelationEvents(categoryId)
  } else {
    form.eventIds = []
  }
}

// 加载已关联赛事
const loadRelationEvents = async (categoryId) => {
  const res = await request.get(`/relations/${categoryId}`)
  form.eventIds = res
}

// 提交表单
const submitForm = async () => {
  try {
    if (!form.categoryId) {
      ElMessage.warning('请选择分类')
      return
    }

    if (!form.eventIds || form.eventIds.length === 0) {
      ElMessage.warning('请选择关联赛事')
      return
    }

    const relation = {
      categoryId: form.categoryId,
      eventIds: form.eventIds
    }

    if (isEdit.value) {
      await request.put('/relations', relation)
    } else {
      await request.post('/relations', relation)
    }

    ElMessage.success('操作成功')
    dialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 删除单个
const deleteRelation = async (id) => {
  if (!id || isNaN(id)) {
    ElMessage.warning('无效的关联ID');
    return;
  }
  try {
    await ElMessageBox.confirm('确定删除该关联吗？', '警告', { type: 'warning' });
    await request.delete(`/relations/${id}`);
    ElMessage.success('删除成功');
    loadData();
  } catch (error) {}
}

// 批量删除
const batchDelete = async () => {
  if (selectedIds.value.length === 0) {
    return ElMessage.warning('请选择要删除的记录')
  }

  try {
    await ElMessageBox.confirm(`确定删除选中的 ${selectedIds.value.length} 项吗？`, '警告')
    await request.delete('/relations/batch', { data: selectedIds.value })
    ElMessage.success('批量删除成功')
    loadData()
  } catch {}
}

// 处理选择
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.categoryId)
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置搜索
const resetSearch = () => {
  searchParams.categoryName = ''
  handleSearch()
}
</script>

<style scoped>
.search-box {
  margin-bottom: 16px;
}

.event-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}

.data-table {
  margin-top: 16px;
}

.el-pagination {
  margin-top: 16px;
  justify-content: flex-end;
}
</style>